package com.iaiai.imail.helper.mail;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 
 * <p>
 * Title: MailMessage.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-9-15 下午4:08:48
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class MailMessage {

	/**
	 * 获得此邮件的Message-ID
	 */
	public static String getMessageId(Message mimeMessage) throws MessagingException {
		return ((MimeMessage) mimeMessage).getMessageID();
	}
	
	/**
	 * 判断此邮件是否已读，如果未读返回返回false,反之返回true
	 */
	public static boolean isNew(Message mimeMessage) throws MessagingException {
		boolean isnew = false;
		Flags flags = mimeMessage.getFlags();
		Flags.Flag[] flag = flags.getSystemFlags();
		for (int i = 0; i < flag.length; i++) {
			if (flag[i] == Flags.Flag.SEEN) {
				isnew = true;
				break;
			}
		}
		return isnew;
	}

	/**
	 * 判断此邮件是否包含附件
	 * @param part
	 * @return true是，false否
	 * @throws Exception
	 */
	public static boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		if (part.isMimeType("multipart/*")) {
			// 如果邮件体包含多部分
			Multipart mp = (Multipart) part.getContent();
			// 遍历每部分
			for (int i = 0; i < mp.getCount(); i++) {
				// 获得每部分的主体
				BodyPart bodyPart = mp.getBodyPart(i);
				String disposition = bodyPart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
					attachflag = true;
				} else if (bodyPart.isMimeType("multipart/*")) {
					attachflag = isContainAttach((Part) bodyPart);
				} else {
					String contype = bodyPart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1) {
						attachflag = true;
					}
					if (contype.toLowerCase().indexOf("name") != -1) {
						attachflag = true;
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			attachflag = isContainAttach((Part) part.getContent());
		}
		return attachflag;
	}

	/**
	 * 判断此邮件是否需要回执，如果需要回执返回"true",否则返回"false"
	 */
	public static boolean getReplySign(Message mimeMessage) throws MessagingException {
		boolean replysign = false;
		String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
		if (needreply != null) {
			replysign = true;
		}
		return replysign;
	}

	/**
	 * 获得邮件发送日期
	 */
	public static Date getSentDate(Message mimeMessage) throws Exception {
		return mimeMessage.getSentDate();
	}

	/**
	 * 获得邮件主题
	 */
	public static String getSubject(Message mimeMessage) throws MessagingException {
		String subject = "";
		try {
			// 将邮件主题解码
			subject = MimeUtility.decodeText(mimeMessage.getSubject());
			if (subject == null) {
				subject = "";
			}
		} catch (Exception exce) {
		}
		return subject;
	}

	/**
	 * 获得发件人的地址和姓名
	 * 
	 * @throws Exception
	 */
	public static String getFrom(Message mimeMessage) throws Exception {
		StringBuilder str = new StringBuilder();
		InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
		if(address!=null){
			for(int i=0;i<address.length;i++){
				// 获得发件人的邮箱
				String from = address[i].getAddress();
				if (from == null) {
					from = "";
				}
				// 获得发件人的描述信息
				String personal = address[i].getPersonal();
				if (personal == null) {
					personal = "";
				}
				// 拼成发件人完整信息
				if(str.length()<=0){
					str.append(personal + "<" + from + ">");
				}else{
					str.append(","+personal + "<" + from + ">");
				}
			}
		}
		return str.toString();
	}

	/**
	 * 获得收件人
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String getTOAddress(Message message) throws Exception {
		return getMailAddress("TO", message);
	}

	/**
	 * 获得抄送人地址
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String getCCAddress(Message message) throws Exception {
		return getMailAddress("CC", message);
	}

	/**
	 * 获得密送人地址
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String getBCCAddress(Message message) throws Exception {
		return getMailAddress("BCC", message);
	}

	/**
	 * 获得邮件地址
	 * 
	 * @param type
	 *            类型，如收件人、抄送人、密送人
	 * @param mimeMessage
	 *            邮件消息
	 * @return
	 * @throws Exception
	 */
	public static String getMailAddress(String type, Message mimeMessage) throws Exception {
		String mailaddr = "";
		String addtype = type.toUpperCase();
		InternetAddress[] address = null;
		if (addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC")) {
			if (addtype.equals("TO")) {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
			} else if (addtype.equals("CC")) {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
			} else {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
			}
			if (address != null) {
				for (int i = 0; i < address.length; i++) {
					// 先获取邮件地址
					String email = address[i].getAddress();
					if (email == null) {
						email = "";
					} else {
						email = MimeUtility.decodeText(email);
					}
					// 再取得个人描述信息
					String personal = address[i].getPersonal();
					if (personal == null) {
						personal = "";
					} else {
						personal = MimeUtility.decodeText(personal);
					}
					// 将个人描述信息与邮件地址连起来
					String compositeto = personal + "<" + email + ">";
					// 多个地址时，用逗号分开
					mailaddr += "," + compositeto;
				}
				mailaddr = mailaddr.substring(1);
			}
		} else {
			throw new Exception("错误的地址类型！!");
		}
		return mailaddr;
	}

	/**
	 * 获得邮件内容
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String getBodyContent(Message message) throws Exception {
		StringBuilder content = new StringBuilder();

		Object obj = message.getContent();

		// 处理多部分邮件
		if (obj instanceof Multipart) {
			for (int j = 0, n = ((Multipart) obj).getCount(); j < n; j++) {

			}
		} else {
			InputStreamReader sbis = null;
			BufferedReader bufr = null;
			try {
				sbis = new InputStreamReader(((Part) message).getInputStream());
				bufr = new BufferedReader(sbis);
				String lineStr = null;
				while (true) {
					lineStr = bufr.readLine(); // 读取我们从键盘输入到控制台的内容
					if (lineStr != null) {
						if (lineStr.equals("over")) // 输入over时结束
						{
							break;
						} else {
							System.out.println(lineStr);
						}
					} else {
						break;
					}
				}
				bufr.close();
				sbis.close();
			} catch (Exception e) {

			}
		}

		return content.toString();
	}

	/**
	 * 获得邮件头类型
	 * 
	 * @param message
	 * @return
	 * @throws MessagingException
	 */
	public static String getContentType(Message message) throws MessagingException {
		return ((Part) message).getContentType();
	}

	/**
	 * 获得邮件描述
	 * 
	 * @param message
	 * @return
	 * @throws MessagingException
	 */
	public static String getDescription(Message message) throws MessagingException {
		return ((Part) message).getDescription();
	}
	
	public static String getDisposition(Message message) throws MessagingException{
		return ((Part) message).getDisposition();
	}

	/**
	 * 邮件大小
	 * 
	 * @param message
	 * @return
	 * @throws MessagingException
	 */
	public static Integer getSize(Message message) throws MessagingException {
		return ((Part) message).getSize();
	}

}
